<?php

/**
 * Date:16-7-18
 * Author: raymond yulong.chen@xici.com
 */
class HnAction extends Action
{

    public $educationMap = [1 => '大专以下', 2 => '大专', 3 => '本科', 4 => '硕士', 5 => '博士'];
    public $jobMap = [1 => '计算机/互联网/通信', 2 => '公务员/事业单位', 3 => '教师', 4 => '医生', 5 => '护士', 6 => '空乘人员',
        7 => '生产/工艺/制造', 8 => '商业/服务业/个体经营', 9 => '金融/银行/投资/保险', 10 => '文化/广告/传媒', 11 => '娱乐/艺术/表演', 12 => '律师/法务',
        13 => '教育/培训/管理咨询', 14 => '建筑/房地产/物业', 15 => '酒店/旅游', 16 => '农业', 17 => '在校学生'];
    public $religionMap = [0 => '无宗教信仰', 1 => '佛教', 2 => '道教', 3 => '基督教', 4 => '伊斯兰教', 5 => '其他'];
    public $constellationMap = [1 => '摩羯', 2 => '水瓶', 3 => '双鱼', 4 => '白羊', 5 => '金牛', 6 => '双子', 7 => '巨蟹', 8 => '狮子', 9 => '处女', 10 => '天秤', 11 => '天蝎', 12 => '射手'];
    public $shengxiaoMap = [1 => '鼠', 2 => '牛', 3 => '虎', 4 => '兔', 5 => '龙', 6 => '蛇', 7 => '马', 8 => '羊', 9 => '猴', 10 => '鸡', 11 => '狗', 12 => '猪'];
    public $maritalMap = [1 => '未婚', 2 => '离异无子女', 3 => '离异不带子女', 4 => '离异带子女', 5 => '丧偶无子女', 6 => '丧偶有子女'];
    public $c_maritalMap = [1 => '未婚', 2 => '离异或丧偶'];
    public $c_educationMap = [2 => '大专及以上', 3 => '本科及以上', 4 => '硕士及以上', 5 => '博士及以上'];

    //代理商

    public function getCity()
    {
        $city = C('CITY');
        Output::instance()->object($city);
    }

    public function getAgentList()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $name = $this->_post('name');
        $province = $this->_post('province');
        $city = $this->_post('city');
        $sort = $this->_post('createTime');
        $start = $this->_post('start');
        $limit = $this->_post('limit');
        $condition['status'] = 1;
        if ($name) {
            $condition['name'] = array('like', '%' . trim($name) . '%');
        }
        if ($city && $city !== '市县') {
            $condition['province'] = $province;
            $condition['city'] = $city;
        }
        $model = M('hongniang_agent');
        $data = $model->where($condition)->order(['createTime' => trim($sort)])->limit($start, $limit)->select();
        $count = $model->where($condition)->count();
        Session::switchCustomer($customerId);
        Output::instance()->objArray($data, $count);
    }

    public function getCustomerById($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        $model = M('customer_user');
        $data = $model->where(['id' => $id])->find();
        Session::switchCustomer($customerId);
        Output::instance()->object(['loginName' => $data['loginName'] ?: '']);
    }

    public function saveAgent()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $result = null;
        $postData = $this->_post();
        $model = M('hongniang_agent');
        $customerUserModel = M('customer_user');
        if (!$postData['id'] && (!trim($postData['loginName']) || !$postData['password'])) {
            Output::instance()->resultCode('1', '请输入登录名和密码！');
            return;
        }
        if (!trim($postData['city'])) {
            Output::instance()->resultCode('1', '请选择城市！');
            return;
        }
        if (!$postData['ratio'] || ($postData['ratio'] < 0 || $postData['ratio'] > 1)) {
            Output::instance()->resultCode('1', '请设置分成比例(0.00~1.00之间)');
            return;
        }
        $res = $customerUserModel->where("loginName='" . trim($postData['loginName']) . "'")->find();
        if ($res && $res['id'] != $postData['uid']) {
            Output::instance()->resultCode('1', '登录名已经存在！');
            return;
        }
        $userData["loginName"] = trim($postData['loginName']);

        if ($postData['password']) {
            $userData["password"] = Encryption::password($postData['password']);
        }
        $userData["status"] = 'open';
        $userData["agent"] = 'hnagent';
        $userData["customerId"] = $customerId;

        $userResult = 0;
        if ($postData['password']) {
            if (intval($postData['uid'])) {
                $userResult = $customerUserModel->where("loginName='" . trim($postData['loginName']) . "'")->save($userData);
            } else {
                $userResult = $customerUserModel->add($userData);
            }
        }
        $agentData = [
            'name' => trim($postData['name']),
            'province' => trim($postData['province']),
            'city' => trim($postData['city']),
            'address' => trim($postData['address']),
            'tel' => trim($postData['tel']),
            'ratio' => $postData['ratio'],
            'status' => 1,
            'uid' => $postData['uid'] ?: $userResult
        ];

        if (intval($postData['id'])) {
            $result = $model->where(['id' => intval($postData['id'])])->find();
            if ($result) {
                $query = $model->where(['id' => intval($postData['id'])])->save($agentData);
                $content_sql = M('hongniang_agent')->getLastSql();
//                $moduleId = M("module_group")->where("name='人人红娘'")->select('id');
//                $sql = $moduleId->query();
//                print_r($sql);die;
                if ($query || $userResult) {
                    Output::instance()->object($postData);
                    R('Log/add', array('hn', '82','人人红娘模块', op_update,$content_sql));
                } else {
                    Output::instance()->resultCode(code_access_denied, "没有修改任何资料,请点击返回按钮");
                }
            }
        } else {
            $agentData['createTime'] = date('Y-m-d H:i:s');
            $row = $model->add($agentData);
            $content_sql = M('hongniang_agent')->getLastSql();
            if ($row) {
                Output::instance()->object($postData);
                R('Log/add', array('hn', '82','人人红娘模块', op_add,$content_sql));
            } else {
                Output::instance()->resultCode(code_access_denied, "添加失败");
            }
        }
    }

    public function deleteAgent($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        $model = M("hongniang_agent");

        $where["id"] = $id;
        $data["status"] = 0;
        $result = $model->where($where)->save($data);
        $content_sql = M('hongniang_agent')->getLastSql();
//        print_r($content_sql);die;
        if ($result) {
            Output::instance()->object(code_success);
            R('Log/add', array('hn', '82','人人红娘模块',  op_delete,$content_sql));
        } else {
            Output::instance()->resultCode(code_sql_error);
            R('Log/add', array('hn', '82','人人红娘模块',  op_delete,$content_sql));
        }
        Session::switchCustomer($customerId);
    }

    //设置

    public function getSetList()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        $start = $this->_post('start');
        $limit = $this->_post('limit');
            $model = M("hongniang_config");
        $result = $model->where(['type' => 'normal'])->order(['display' => 'asc'])->limit($start, $limit)->select();
        if ($result) {
            $data = [];
            foreach ($result as $v) {
                if ($v['pk'] === 'position') {
                    $v['value'] = json_decode($v['value'], true);
                }
                $data[] = $v;
            }
            Output::instance()->objArray($data);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }

    public function getAgreement()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);;
        $model = M("hongniang_config");
        $result = $model->where(['pk' => 'agreement'])->find();
        if ($result) {
            Output::instance()->objArray($result);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }

    public function updateConfig()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);


        $pool = ['discoverRecommendedNumber', 'matchingCommission', 'recommendedRewardRatio', 'registrationCommission',
            'rewardRatio', 'subRecommendedRewardRatio', 'successCommission', 'systemRecommendedNumber', 'agreement', 'position', 'background'];
        $key = $this->_post('key');
        if (!in_array($key, $pool)) {
            Output::instance()->resultCode('1', '配置项不存在');
            return;
        }
        $value = $this->_post('value');
        switch ($key) {
            case 'discoverRecommendedNumber':
            case 'matchingCommission':
            case 'registrationCommission':
            case 'successCommission':
            case 'systemRecommendedNumber':
                if (!is_numeric($value)) {
                    Output::instance()->resultCode(1, '请填写整数');
                    return;
                }
                break;
            case 'recommendedRewardRatio':
            case 'rewardRatio':
            case 'subRecommendedRewardRatio':
                if ($value < 0 || $value > 1) {
                    Output::instance()->resultCode(1, '请填写小数,区间 [0,1]');
                    return;
                }
                break;
            case 'position':
                $value = json_encode($value);
                break;
            case 'background':

                break;

        }
        $data = ['value' => trim($value)];

        $model = M("hongniang_config");
        $return = $model->where(['pk' => $key])->save($data);

        if($key === 'background' && $return){
            M('hongniang_matchmaker')->where([])->save(['qrimg'=>'']);
        }

        Output::instance()->resultCode(code_success);
        Session::switchCustomer($customerId);
    }

    public function getLove()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer($customerId);
        $weixinModel = M("user_weixin_info");
        Session::switchCustomer(0);

        $nickname = $this->_post('nickname');
        $verify = $this->_post('verify');

        $start = $this->_post('start');
        $limit = $this->_post('limit');

        $where = [];
        if ($nickname) {
            $where['wx.nickname'] = ['like', '%' . trim($nickname) . '%'];
        }
        if (isset($verify) && in_array($verify, [0, 1])) {
            $where['hn.verify'] = intval($verify);
        }

        $model = M("hongniang_love");
        $result = $model->alias('hn')->join("wx_" . $customerId . "_user_weixin_info wx ON hn.uid = wx.id")->where($where)->field("hn.*,wx.nickname,wx.headimgurl")->order(['createTime' => 'desc'])->limit($start, $limit)->select();
        $count = $model->alias('hn')->join("wx_" . $customerId . "_user_weixin_info wx ON hn.uid = wx.id")->where($where)->count();
        $list = [];
//下列查询可先收集ID再统一查询，时间充裕可优化
        foreach ((array)$result as $item) {
            $item['matchmakerName'] = '';
            $item['matchmakerAvatar'] = '';
            if ($item['matchmakerId']) {
                $row = $weixinModel->where(['id' => $item['matchmakerId']])->find();
                if ($row['nickname']) {
                    $item['matchmakerName'] = $row['nickname'];
                    $item['matchmakerAvatar'] = $row['headimgurl'];
                }
            }
            $item['vipName'] = '';
            if ($item['agent']) {
                $row = M('hongniang_agent')->where(['id' => intval($item['agent'])])->find();
                $item['vipName'] = $row['name'];
            }
            $list[] = $item;
        }
        Session::switchCustomer(0);
        if ($result) {
            Output::instance()->objArray($list, $count);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }

    public function getLoveDetailById($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        if ($id) {
            $info = M('hongniang_love')->where(['id' => $id])->find();
            $condition = M('hongniang_condition')->where(['uid' => $info['uid']])->find();
            $info['educationTxt'] = $this->educationMap[$info['education']];
            $info['jobTxt'] = $this->jobMap[$info['job']];
            $info['religionTxt'] = $this->religionMap[$info['religion']];
            $info['shengxiaoTxt'] = $this->shengxiaoMap[$info['shengxiao']] ?: '未知';
            $info['constellationTxt'] = $this->constellationMap[$info['constellation']] ?: '未知';
            $info['maritalTxt'] = $this->maritalMap[$info['marital']] ?: '未知';
            if ($condition) {
                $info['c_minAge'] = $condition['maxAge'] ? date('Y') - $condition['maxAge'] : '不限';
                $info['c_maxAge'] = $condition['minAge'] ? date('Y') - $condition['minAge'] : '不限';
                $info['c_minHeight'] = $condition['minHeight'] ?: '不限';
                $info['c_maxHeight'] = $condition['maxHeight'] ?: '不限';
                $info['c_minWeight'] = $condition['minWeight'] ?: '不限';
                $info['c_maxWeight'] = $condition['maxWeight'] ?: '不限';
                $info['c_minEarning'] = $condition['minEarning'] ?: '不限';
                $info['c_maxEarning'] = $condition['maxEarning'] ?: '不限';
                $info['c_areaTxt'] = $condition['area'] ? C('CITY')[$condition['area']] : '不限';
                $info['c_maritalTxt'] = $condition['marital'] ? $this->c_maritalMap[$condition['marital']] : '不限';
                $info['c_educationTxt'] = $condition['education'] ? $this->c_educationMap[$condition['education']] : '不限';
            }
        }
        if ($info) {
            Output::instance()->object($info);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public function lovePass()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $result = null;
        $id = $this->_post('id');
        $user = M('hongniang_love')->where(['id' => $id])->find();
        if ($user && $user['verify'] == 1) {
            Output::instance()->resultCode(code_access_denied, "已经核验过了");
        }
        $result = M('hongniang_love')->where(['id' => $id])->save(['verify' => 1]);
        R('Log/add', array('hn', NULL, op_update, '核验通过'));
        Output::instance()->resultCode(0, "操作成功");
    }

    public function getMatchmaker()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer($customerId);
        $weixinModel = M("user_weixin_info");
        Session::switchCustomer(0);

        $nickname = $this->_post('nickname');
        $refereeName = $this->_post('refereeName');

        $start = $this->_post('start');
        $limit = $this->_post('limit');

        $where = [];
        $model = M("hongniang_matchmaker");
        if ($nickname) {
            $where['wx.nickname'] = ['like', '%' . trim($nickname) . '%'];

        }
        $pool = [];
        if ($refereeName) {
            $temp = $weixinModel->where(['nickname' => ['like', '%' . trim($refereeName) . '%']])->select();
            if (count($temp)) {
                foreach ($temp as $item) {
                    $pool[] = $item['id'];
                }
            }
            $pool = $pool ?: [-1];
            $where['hn.refereeId'] = ['in', $pool];
        }

        $result = $model->alias('hn')->join("wx_" . $customerId . "_user_weixin_info wx ON hn.uid = wx.id")->where($where)->field("hn.*,wx.nickname,wx.headimgurl")->order(['createTime' => 'desc'])->limit($start, $limit)->select();
        $count = $model->alias('hn')->join("wx_" . $customerId . "_user_weixin_info wx ON hn.uid = wx.id")->where($where)->count();
        $list = [];
//下列查询可先收集ID再统一查询，时间充裕可优化
        foreach ((array)$result as $item) {
            $item['refereeName'] = '';
            $item['refereeAvatar'] = '';
            if ($item['refereeId']) {
                $row = $weixinModel->where(['id' => $item['refereeId']])->find();
                if ($row['nickname']) {
                    $item['refereeName'] = $row['nickname'];
                    $item['refereeAvatar'] = $row['headimgurl'];
                }
            }

            $list[] = $item;
        }
        Session::switchCustomer(0);
        if ($result) {
            Output::instance()->objArray($list, $count);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }

    public function getAccountIncome()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];

        $start = $this->_post('start');
        $limit = $this->_post('limit');

        $uid = $this->_get('uid');

        Session::switchCustomer(0);
        $model = M('hongniang_earning');
        $data = $model->where(['uid' => $uid])->limit($start, $limit)->select();
        if ($data) {
            Output::instance()->objArray($data);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public function getAccountWithdraw()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];

        $start = $this->_post('start');
        $limit = $this->_post('limit');

        $uid = $this->_get('uid');

        Session::switchCustomer(0);
        $model = M('hongniang_withdraw');
        $data = $model->where(['uid' => $uid])->limit($start, $limit)->select();
        if ($data) {
            Output::instance()->objArray($data);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public function systemWithdraw()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];

        $start = $this->_post('start');
        $limit = $this->_post('limit');

        Session::switchCustomer(0);
        $model = M('hongniang_withdraw');
        $data = $model->alias('w')->join("wx_hongniang_matchmaker m ON w.uid = m.uid")->join("wx_" . $customerId . "_user_weixin_info u ON w.uid = u.id")->limit($start, $limit)->field("w.*,m.balance,u.nickname,u.headimgurl")->select();
        if ($data) {
            Output::instance()->objArray($data);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public function processWithdraw()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $id = $this->_post('id');
        $model = M('hongniang_withdraw');
        $row = $model->where(['id' => intval($id)])->find();
        if ($row) {
            $openId = $row['openId'];
            $cash = $row['cash'];
            $func = M('customer_mall_setting')->where(['customerId' => $customerId])->find();
            if (!$func) {
                Output::instance()->resultCode(1, '功能设置不存在');
                return;
            }
            $result = WeixinApi::transferAccountsByOpenId($openId, $cash, '红娘提现', false, $func['payKey'], $func['mchId'], $func['appId']);

            if ($result) {
                M('hongniang_withdraw')->where(['id' => $id])->save(['status' => 1]);
                Output::instance()->resultCode(code_success);
            } else {
                Output::instance()->resultCode(1, '提现失败');
            }
        } else {
            Output::instance()->resultCode(1, '该流水已经不存在了');
        }


    }

    public function packageList()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];

        $start = $this->_post('start');
        $limit = $this->_post('limit');

        Session::switchCustomer(0);
        $model = M('hongniang_package');
        $data = $model->where(['status' => 1])->limit($start, $limit)->select();
        if ($data) {
            Output::instance()->objArray($data);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public function savePackage()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $result = null;
        $postData = $this->_post();
        $model = M('hongniang_package');
        if (!$postData['name'] || !$postData['money'] || !$postData['num']) {
            Output::instance()->resultCode('1', '请完善必填字段');
            return;
        }
        $packageData = [
            'name' => trim($postData['name']),
            'money' => trim($postData['money']),
            'num' => trim($postData['num']),
            'remark' => $postData['remark'],
            'status' => 1
        ];

        if (intval($postData['id'])) {
            $result = $model->where(['id' => intval($postData['id'])])->find();
            if ($result) {
                $query = $model->where(['id' => intval($postData['id'])])->save($packageData);
                if ($query) {
                    Output::instance()->object($postData);
                    R('Log/add', array('hn', NULL, op_update, '更新套餐信息'));
                } else {
                    Output::instance()->resultCode(code_access_denied, "没有修改任何资料,请点击返回按钮");
                }
            }
        } else {
            $row = $model->add($packageData);
            if ($row) {
                Output::instance()->object($postData);
                R('Log/add', array('hn', NULL, op_add, '添加套餐信息'));
            } else {
                Output::instance()->resultCode(code_access_denied, "添加失败");
            }
        }
    }

    public function delPackage($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        $model = M("hongniang_package");

        $where["id"] = $id;
        $data["status"] = 0;
        $result = $model->where($where)->save($data);
        if ($result) {
            Output::instance()->object(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }
}